package com.weibo.framework.core.counter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import com.weibo.framework.core.model.CounterModel;

/**
 * 统计行数业务类 只统计Java代码注释
 * @author fattiger.xiaoyang
 * @date 2016/03/22
 */
public class JavaCounter implements Counter {

	public CounterModel getCounter(File file) {
		BufferedReader reader = null;
		CounterModel codeCounter = new CounterModel();
		
        long totalLineNo = 0;
        long codeLineNo = 0;
        long blankLineNo = 0;
        long commentLineNo = 0;
        
        try {
        	//开始读取文件
            reader = new BufferedReader(new FileReader(file));
            String strLine = null;
            //是否为注释
            boolean isComment = false;
            while ((strLine = reader.readLine()) != null) {
                totalLineNo++;

                if (strLine == null || strLine.trim().equals("")) {
                    blankLineNo++;
                    continue;
                }

                if (strLine.trim().endsWith("*/")) {
                    isComment = false;
                    commentLineNo++;
                    continue;
                }

                if (isComment) {
                    commentLineNo++;
                    continue;
                }

                if (strLine.trim().startsWith("/*") && strLine.trim().endsWith("*/")) {
                    commentLineNo++;
                    isComment = true;
                    continue;
                }
                
                if (strLine.trim().startsWith("/*")) {
                    commentLineNo++;
                    isComment = true;
                    continue;
                }

                if (strLine.trim().startsWith("//")) {
                    commentLineNo++;
                    continue;
                }

                codeLineNo++;
            }

            codeCounter.setTotalLineNo(totalLineNo);
            codeCounter.setCodeLineNo(codeLineNo);
            codeCounter.setBlankLineNo(blankLineNo);
            codeCounter.setCommentLineNo(commentLineNo);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                	e1.printStackTrace();
                    return null;
                }
            }
        }
        return codeCounter;
	}

}
